/*
 * Copyright 2012 nekdo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.heathtow.rest;

import com.google.gson.Gson;
import com.sun.jersey.spi.inject.Inject;
import cz.muni.fi.heathrowapi.AircraftService;
import cz.muni.fi.heathrowapi.dto.AircraftDTO;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 *
 * @author Jan Richter
 */
@Component
@Path("/aircraft")
@Scope("request")
public class AircraftResourceImpl implements AircraftResource {

    @Inject
    private AircraftService aircraftService;
    @Context
    UriInfo info;

    @Override
    @GET
    @Produces("application/json")
    public String getAircrafts() {
        try {
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            return new Gson().toJson(aircraftService.findAll());
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }

    @Override
    @GET
    @Path("/{id}")
    @Produces("application/json")
    public String getAircraft(@PathParam("id") String id) {
        try {
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            return new Gson().toJson(aircraftService.get(Long.parseLong(id)));
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }

    @Override
    @GET
    @Path("/code/{code}")
    @Produces("application/json")
    public String getAircraftByCode(@PathParam("code") String code) {
        try {
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            return new Gson().toJson(aircraftService.findByCode(code));
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }

    @Override
    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces("text/plain")
    public String updateAircraft(String json) {
        try {
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            AircraftDTO update = new Gson().fromJson(json, AircraftDTO.class);
            aircraftService.update(update);
            return "success";
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }

    @Override
    @POST
    @Produces("text/plain")
    @Consumes(MediaType.APPLICATION_JSON)
    public String createAircraft(String json) {
        try {
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            AircraftDTO air = new Gson().fromJson(json, AircraftDTO.class);
            aircraftService.create(air);
            return "success";
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }

    @Override
    @DELETE
    @Path("/{id}")
    @Produces("text/plain")
    @Consumes("text/plain")
    public String deleteAircraft(@PathParam("id") String id) {
        try {
            authenticate(RestAuthentication.REST_USERNAME, RestAuthentication.REST_PASSWORD);
            AircraftDTO aircraft = aircraftService.get(Long.parseLong(id));
            if (aircraft != null) {
                aircraftService.remove(aircraft);
            }
            return "success";
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }
    
    private void authenticate(String username, String password){
        Authentication authentication = new UsernamePasswordAuthenticationToken(username, password);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
